#!/usr/bin/python

import sys
import os


def parse_daemons_dir(dir_path):
    daemons = {}

    for (path, b, filenames) in os.walk(work_dir):
        if "start" in filenames:
            with open(path + "/start") as f:
                name = f.readline().strip()
                deps = f.readline().split()
                if deps == ["none"]:
                    deps = []
                command = f.readline()

                daemons[name] = [deps, command]

    return daemons


def find_daemon_level(name, daemons):
    if len(daemons[name][0]) == 0:
        return 0

    return max(find_daemon_level(x, daemons) for x in daemons[name][0]) + 1


def build_queue(daemons):
    queue = sorted([daemon for daemon in daemons],
                   key=lambda x: find_daemon_level(x, daemons))

    return queue


if len(sys.argv) < 2:
    exit(2)


work_dir = sys.argv[1]
if not os.path.isdir(work_dir):
    exit(2)

daemons = parse_daemons_dir(work_dir)
print(build_queue(daemons))
